package com.supplychain.scm.core.common.validator.file;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.ArrayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @author liyichuan
 * @date 2022/06/11
 */
@Slf4j
public class FileTypeConstraintValidator implements ConstraintValidator<FileType, MultipartFile> {

    private Set<String> vals = new HashSet<>();
    /**
     * 校验器初始化
     * @param constraintAnnotation
     */
    @Override
    public void initialize(FileType constraintAnnotation) {
        //获取注解的中制定的值
        String[] value = constraintAnnotation.value();
        if(ArrayUtil.isNotEmpty(value)){
            for (String i : value) {
                vals.add(i);
            }
        }

    }


    @Override
    public boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext constraintValidatorContext) {
        // 空不做校验
        if(null == multipartFile){
            return true;
        }
        try {
            String type = FileTypeUtil.getType(multipartFile.getInputStream());
            return vals.contains(type);
        } catch (IOException e) {
           log.error("文件校验异常",e);
        }
        return false;
    }
}
